package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 分布式锁
 * @author benxin
 */
public class RedisLock implements ILock{
    private StringRedisTemplate stringRedisTemplate;

    private String name;

    public RedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    private static final String KEY_PREFIX = "lock:";
    // 用 UUID 来防止多个端口线程名称重复冲突
    private static final String ID_PREFIX = UUID.randomUUID() + "-";

    /**
     * 尝试获取锁
     * @param timeoutSec 锁的过期时间，超时后自动释放
     * @return
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        // 获取线程唯一标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 尝试获取锁并判断是否获取成功
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(success);
    }

    /**
     * 释放锁
     */
    @Override
    public void unlock() {
        // 获取线程唯一标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁中的标识
        String lockId = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        // 对比线程唯一标识
        if(threadId.equals(lockId)) {
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }

    }
}
